import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Upload from '../views/Upload.vue'
import History from '../views/History.vue'
import Search from '../views/Search.vue'
import Detail from '../views/Detail.vue'
import Login from '../views/Login.vue'
import SequenceSearch from '../views/SequenceSearch.vue'
import StructureSearch from '../views/StructureSearchEnhanced.vue'
import ArcChat from '../views/ArcChat.vue'
import Admin from '../views/Admin.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { title: '首页', public: true }
  },
  {
    path: '/search',
    name: 'Search',
    component: Search,
    meta: { title: '搜索数据', public: true }
  },
  {
    path: '/sequence-search',
    name: 'SequenceSearch',
    component: SequenceSearch,
    meta: { title: '序列搜索', public: true }
  },
  {
    path: '/structure-search',
    name: 'StructureSearch',
    component: StructureSearch,
    meta: { title: '结构搜索', public: true }
  },
  {
    path: '/protein/:id',
    name: 'Detail',
    component: Detail,
    meta: { title: '蛋白质详情', public: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '管理员登录', public: true }
  },
  {
    path: '/upload',
    name: 'Upload',
    component: Upload,
    meta: { title: '上传数据', requiresAuth: true }
  },
  {
    path: '/history',
    name: 'History',
    component: History,
    meta: { title: '导入历史', requiresAuth: true }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: Admin,
    meta: { title: '管理员面板', requiresAuth: true }
  },
  {
    path: '/arcchat',
    name: 'ArcChat',
    component: ArcChat,
    meta: { title: 'arcCHAT', public: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  document.title = `${to.meta.title || ''} - 蛋白质数据库管理系统`
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('admin_token')
    const tokenExpires = localStorage.getItem('token_expires')
    
    if (!token || !tokenExpires) {
      // 没有token，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 检查token是否过期
    if (Date.now() > parseInt(tokenExpires)) {
      // token过期，清除并跳转到登录页
      localStorage.removeItem('admin_token')
      localStorage.removeItem('token_expires')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }
  
  next()
})

export default router


